package com.platform.schedule.dynamic.service.impl;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.concurrent.ScheduledFuture;

/**
 * <p>
 *
 * @author: WangYang
 * @date: 2017-12-26 17:42
 * @version: 1.0
 * @since 1.8
 */
@Slf4j
public class DynamicScheduleTemplate {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    /**
     *
     */
    private ScheduledFuture future;
    /**
     * 任务Bean
     */
    @Setter
    private Object bean;
    /**
     * 执行方法名称
     */
    @Setter
    private String methodName;
    /**
     * 定时任务名称
     */
    @Getter
    @Setter
    private String name;
    /**
     * 定时器表达式
     */
    @Getter
    @Setter
    private String cron = "";

    @PostConstruct
    public void init() {
        run();
    }

    public void run() {
        future = threadPoolTaskScheduler.schedule(() -> {
                    try {
                        Method method = bean.getClass().getMethod(methodName);
                        method.invoke(bean);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                },
                triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext)
        );
    }

    public void cancel() {
        if (null != future) {
            future.cancel(true);
        }
    }

    public void cron() {
        cancel();
        run();
    }

}
